<!DOCTYPE html>
<html lang="en">
<head>
	<title>Xterm</title>
	<link rel="stylesheet" href="/main.css" />
	<link rel="stylesheet" href="/xterm.js/src/xterm.css" />
	<link rel="stylesheet" href="/xterm.js/addons/fullscreen/fullscreen.css" />
</head>
<body>
	<div id="terminal-container"></div>

	<script src="/xterm.js/src/xterm.js" ></script>
	<script src="/xterm.js/addons/fit/fit.js" ></script>
	<script src="/xterm.js/addons/fullscreen/fullscreen.js" ></script>
	<script>
		console.log('000000',document.body.clientWidth,document.body.clientHeight,document.body.clientLeft,document.body.clientTop,document.body.getBoundingClientRect().width,document.body.getBoundingClientRect().height)
	var term;
	var websocket = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/term");
	websocket.binaryType = "arraybuffer";

	function ab2str(buf) {
		return String.fromCharCode.apply(null, new Uint8Array(buf));
	}
	Terminal.applyAddon(fit);
	Terminal.applyAddon(fullscreen);

	websocket.onopen = function(evt) {
		term = new Terminal({
			screenKeys: true,
			useStyle: true,
			cursorBlink: true,
			// letterSpacing: 0.5,
			// cols: 50,
			// rows: 50,
			// cursorBlink: 5,
			scrollback: 100,
			tabStopWidth: 4,
		});

		term.on('data', function(data) {
			websocket.send(new TextEncoder().encode("\x00" + data));
		});

		term.on('resize', function(evt) {
			console.log('1111',evt)
			websocket.send(new TextEncoder().encode("\x01" + JSON.stringify({cols: evt.cols, rows: evt.rows})))
		});

		term.on('title', function(title) {
			document.title = title;
		});

		term.open(document.getElementById('terminal-container'));
	    term.fit();
		term.toggleFullScreen(true);  // Now the terminal should be back to normal
		// term.toggleFullScreen(false);  // Now the terminal should be back to normal
		websocket.onmessage = function(evt) {
		if (evt.data instanceof ArrayBuffer) {
			term.write(ab2str(evt.data));
		} else {
			alert(evt.data)
		}


	}

	websocket.onclose = function(evt) {
		term.write("Session terminated");
		term.destroy();
	}

	websocket.onerror = function(evt) {
		if (typeof console.log == "function") {
			console.log(evt)
		}
	}
	}
	</script>
</body>
</html>
